package com.vector.ding.web.service.baseinfo;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.ActionResult;
import com.vector.ding.commons.BizConstant;
import com.vector.ding.commons.Constant;
import com.vector.ding.commons.util.BeanUtil;
import com.vector.ding.commons.util.NumberUtil;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.commons.util.file.ExcelUtil;
import com.vector.ding.commons.util.web.RequestUtil;
import com.vector.ding.dao.mybatis.mapper.RzzlgsBaseInfoMapper;
import com.vector.ding.dao.mybatis.model.RzzlgsBaseInfo;
import com.vector.ding.dao.mybatis.model.RzzlgsBaseInfoExample;
import com.vector.ding.exception.BaseException;

@Service
public class RzzlgsBaseInfoMgrService {
	
	private static Logger logger = LoggerFactory.getLogger(GqtzgsBaseInfoMgrService.class);

	@Autowired
	private RzzlgsBaseInfoMapper baseMapper;
	
	public RzzlgsBaseInfo getBaseInfo(String number) {
		return baseMapper.selectByPrimaryKey(number);
	}
	
	public RzzlgsBaseInfo getBaseInfoByName(String companyName) {
		RzzlgsBaseInfoExample example = new RzzlgsBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		List<RzzlgsBaseInfo> list = baseMapper.selectByExample(example);
		return CollectionUtil.isEmpty(list) ? null : list.get(0);
	}
	
	public List<RzzlgsBaseInfo> getBaseInfo(int pageIndex, int pageSize, 
			HttpServletRequest request) {
		if (pageSize != Integer.MAX_VALUE)
			PageHelper.startPage(pageIndex, pageSize, true);
		RzzlgsBaseInfoExample example = getBaseInfoExample(request);
		//example.setOrderByClause("number asc");
		return baseMapper.selectByExample(example);
	}
	
	private RzzlgsBaseInfoExample getBaseInfoExample(HttpServletRequest request) {
		RzzlgsBaseInfoExample example = new RzzlgsBaseInfoExample();
		String companyName = StringUtil.getString(request.getParameter("company_name")).trim();
		//if (StringUtil.isNotEmpty(companyName))
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return example;
	}
	
	public RzzlgsBaseInfo getBaseInfoBean(HttpServletRequest request) {
		Map<String, Object> paramMap = RequestUtil.getParamMap(request);
		Set<String> excludeProSet = CollectionUtil.asSet(
				"registerFund");
		RzzlgsBaseInfo baseInfo = new RzzlgsBaseInfo();
		BeanUtil.fillBeanProperty(paramMap, baseInfo, excludeProSet);
		baseInfo.setRegisterFund(NumberUtil.getBigDecimal(paramMap.get("registerFund")));
		if (StringUtil.isEmpty(baseInfo.getNumber()))
			baseInfo.setNumber(StringUtil.getUuid());

		return baseInfo;
	} 
	
	public void importFormFile(File importFile) {
		HSSFWorkbook workBook = null;
		int rowIndex = 0;
		try {
			workBook = new HSSFWorkbook(FileUtils.openInputStream(importFile));
			HSSFSheet sheet = workBook.getSheetAt(0);
			HSSFRow titleRow = sheet.getRow(0);
			for (int cellIdx = titleRow.getFirstCellNum(); cellIdx < titleRow.getLastCellNum(); ++cellIdx) {
				System.out.println(titleRow.getCell(cellIdx).toString());
			}
			int rowNum = sheet.getLastRowNum();
			for (rowIndex = 1; rowIndex <= rowNum; ++rowIndex) {
				HSSFRow row = sheet.getRow(rowIndex);
				boolean needImport = checkRowData(row);
				if (!needImport)
					continue;
				
				RzzlgsBaseInfo bean = getBaseInfoBean(row);
				baseMapper.insertSelective(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
//			throw new BaseException(e);
			throw new BaseException(String.format("第%s行数据格式有误，请检查数据！", rowIndex));
		} finally {
			if (workBook != null) {
				try {
					workBook.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BaseException(e);
				}
			}
		}
	}
	
	public RzzlgsBaseInfo getBaseInfoBean(HSSFRow row) {
		RzzlgsBaseInfo bean = new RzzlgsBaseInfo();
		//bean.setAddress(row.getCell(BizConstant.Rzzlgs.Base.));
		bean.setCompanyName(row.getCell(BizConstant.Rzzlgs.Base.COMPANY_NAME_CELL).toString());
		bean.setCompanyType(row.getCell(BizConstant.Rzzlgs.Base.COMPANY_TYPE_CELL).toString());
		bean.setDelegateName(row.getCell(BizConstant.Rzzlgs.Base.DELEGATE_PEOPLE_CELL).toString());
		bean.setEstablishDate(ExcelUtil.getDateString(row.getCell(BizConstant.Rzzlgs.Base.ESTABLISH_DATE_CELL)));
		bean.setNumber(StringUtil.getUuid());
		bean.setRegisterAddress(row.getCell(BizConstant.Rzzlgs.Base.REG_ADDRESS_CELL).toString());
		bean.setRegisterCurrency(row.getCell(BizConstant.Rzzlgs.Base.REG_CURRENCY_CELL).toString());
		try {
			bean.setRegisterFund(new BigDecimal(row.getCell(BizConstant.Rzzlgs.Base.REG_FUND_CELL).toString()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		bean.setRegisterLocation(row.getCell(BizConstant.Rzzlgs.Base.REG_LOCATION_CELL).toString());
		//bean.setRegisterNumber(registerNumber);
		
		return bean;
	}
	
	private boolean checkRowData(HSSFRow row) {
//		HSSFCell numberCell = row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL);
//		if (numberCell == null)
//			return false;
//		String stringValue = row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL).toString();
//		if (StringUtil.isEmpty(stringValue))
//			return false;
//		String number = StringUtil.getString((int)row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL).getNumericCellValue());
//		if (StringUtil.isEmpty(number))
//			return false;
		
		HSSFCell nameCell = row.getCell(BizConstant.Rzzlgs.Base.COMPANY_NAME_CELL);
		if (nameCell == null)
			return false;
		String companyName = nameCell.toString();
		
		return !existsCompany(companyName);
	}

	public JSONObject delete(String[] ids) {
		int count = Constant.DaoOperation.UPDATE_FAILURE ;
		if (ids == null || ids.length == 0)
			count = 0;
		
		try {
			for (String id: ids) {
				count += baseMapper.deleteByPrimaryKey(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (count == Constant.DaoOperation.UPDATE_FAILURE)
			return ActionResult.fail("删除失败！");
		return ActionResult.success();
	}

	public JSONObject updateBaseInfo(RzzlgsBaseInfo baseInfo) {
		if (!existRecord(baseInfo.getNumber()))
			return ActionResult.fail(String.format("更新失败：不存在编号为[%s]的记录!", baseInfo.getNumber()));
		int cnt = 0;
		try {
			cnt = baseMapper.updateByPrimaryKeySelective(baseInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (cnt == 0) {
			logger.error("更新股权投资公司基本信息记录失败：未找到number为{}的记录...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? ActionResult.success() : 
			ActionResult.fail(String.format("更新基本信息记录失败，编号为[%s]", baseInfo.getNumber()));
	}

	public JSONObject insertBaseInfo(RzzlgsBaseInfo baseInfo) {
		if (existRecord(baseInfo.getNumber()))
			return ActionResult.fail(String.format("新增失败：存在编号为[%s]的记录!", baseInfo.getNumber()));
		
		int cnt = 0;
		try {
			cnt = baseMapper.insertSelective(baseInfo);
		} catch (Exception e) {
			if (logger.isDebugEnabled())
				e.printStackTrace();
		}
		if (cnt == 0) {
			logger.error("插入股权投资公司基本信息记录失败：number为{}...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? ActionResult.success() : 
			ActionResult.fail(String.format("新增记录失败"));
	}
	
	public boolean existRecord(String number) {
		RzzlgsBaseInfoExample example = new RzzlgsBaseInfoExample();
		example.or().andNumberEqualTo(number);
		return baseMapper.countByExample(example) != 0;
	}
	
	public boolean existsCompany(String companyName) {
		RzzlgsBaseInfoExample example = new RzzlgsBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		return baseMapper.countByExample(example) > 0 ? true : false;
	}
}
